package com.woniu.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.woniu.entity.PageResult;
import com.woniu.entity.Result;
import com.woniu.entity.dto.CarTypeSearchDTO;
import com.woniu.mapper.CarTypeMapper;
import com.woniu.pojo.CarType;
import com.woniu.service.ICarTypeService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author tarnett
 */
@Service
public class CarTypeServiceImpl implements ICarTypeService {

    @Resource
    private CarTypeMapper carTypeMapper;

    @Override
    public PageResult<CarType> listSearch(CarTypeSearchDTO carTypeSearchDTO) {
        // 1. 开启分页
        PageHelper.startPage(carTypeSearchDTO.getCurrentPage(), carTypeSearchDTO.getPageSize());
        // 2. 调用mapper查询数据
        Page<CarType> page = carTypeMapper.listSearch(carTypeSearchDTO);
        // 3. 封装分页对象
        PageResult<CarType> pageResult = new PageResult<>();
        pageResult.setTotal(page.getTotal());
        pageResult.setData(page.getResult());
        // 4. 返回数据
        return pageResult;
    }

    @Override
    public Result save(CarType carType) {
        // 判断名称是否已经存在
        CarType carType1 = checkNameExist(carType.getName());
        if(carType1 != null){
            return Result.error("该名称已经存在");
        }
        return Result.commonByRow(carTypeMapper.save(carType));
    }

    @Override
    public Integer deleteByIds(Long[] ids) {
        return carTypeMapper.deleteByIds(ids);
    }

    @Override
    public Result updateById(CarType carType) {
        // 判断名称是否已经存在
        CarType carType1 = checkNameExist(carType.getName());
        if(carType1 != null && !carType1.getId().equals(carType.getId())){
            return Result.error("该名称已经存在");
        }
        return Result.commonByRow(carTypeMapper.updateById(carType));
    }

    @Override
    public CarType getById(Long id) {
        return carTypeMapper.getById(id);
    }

    @Override
    public CarType checkNameExist(String name) {
        return carTypeMapper.checkNameExist(name);
    }

    @Override
    public List<CarType> listAll() {
        return carTypeMapper.listAll();
    }
}
